/**
 *  common
 *  wxservice get wx js-sdk signature
 *      获取 js sdk
 *      设置分享
 *      屏蔽分享
 */

let vue = require("vue");
let wx = require("weixin-js-sdk");
let common = require("./common.js");
export default {
  /**
   * 朋友圈 菜单列表
   */
  menuListTemplate: [
    "menuItem:share:appMessage",
    "menuItem:share:timeline",
    "menuItem:share:qq",
    "menuItem:share:weiboApp",
    "menuItem:favorite",
    "menuItem:share:facebook",
    "menuItem:share:QZone",
    "menuItem:editTag",
    "menuItem:delete",
    "menuItem:copyUrl",
    "menuItem:originPage",
    "menuItem:readMode",
    "menuItem:openWithQQBrowser",
    "menuItem:openWithSafari",
    "menuItem:share:email",
    "menuItem:share:brand"
  ],
  _initJsSDK(
    {
      appId = "",
      debug = false,
      jsApiList = [],
      nonceStr = "",
      signature = "",
      timestamp = 0
    } = {},
    params = {}
  ) {
    let config = {
      appId,
      debug,
      jsApiList,
      nonceStr,
      signature,
      timestamp
    };
    console.log(appId);
    if (appId == "" || nonceStr == "" || signature == "" || timestamp == 0) {
      throw new Error("Missing parameter");
    }

    Object.assign(config, {
      debug: false,
      jsApiList: [
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "onMenuShareQQ",
        "onMenuShareWeibo",
        "hideMenuItems",
        "showMenuItems",
        "chooseImage",
        "previewImage",
        "uploadImage"
      ]
    });
    return new Promise((resolve, reject) => {
      wx.config(config);
      wx.ready(function() {
        resolve();
      });
      wx.error(response => {
        reject("wx.config失败:" + JSON.stringify(response));
      });
    });
  },
  /**
   * 获取js-sdk签名,并且加载微信js
   * @param apiUrl 请求地址
   * @param params 参数
   *     openid: 用户的openid.  与enterpriseId 二者必有一个存在
   *     enterpriseId: 用户的企业id 与openid 二者必有一个存在
   *     beat: 是否要调用beat版的接口
   *     jsApiList: 而外需要传入的jsApiList
   * @returns {boolean}
   *
   *     ex:
   *     wsService.getJsSDK('http://mp.yunlai.cn/mp/getJsconfigV2', {
   *          params: {
   *               openid: 'oiJlaxHPYEAe7Y34HKIuDajk7-fY',
   *               enterpriseId: 1,
   *               beat: true,
   *               jsApiList: ['openEnterpriseChat','openEnterpriseContact','enterEnterpriseChat','sendEnterpriseChat']
   *           }
   *       }).then(() => {
   *          console.log(123123);
   *       });
   */
  getJsSDK(apiUrl = "", { params = {} } = {}) {
    let locationUrl = location.href,
      obj = { url: locationUrl };
    return new Promise((resolve, reject) => {
      let id = common.getCookie("sessionId");
      let api = apiUrl + "?sessionId=" + id;
      vue.default.http.post(api, obj, { emulateJSON: true }).then(
        ({ data: { data } }) => {
          if (!wx) {
            reject("wx undefined");
            return;
          }
          this._initJsSDK(data.bussData, params).then(() => {
            resolve();
          });
        },
        response => {
          console.log("getJsSDKError:" + JSON.stringify(response));
          console && console.error && console.error("servers-wx-jssdk: 137");
          reject("getJsSDKError");
        }
      );
    });
  },
  /**
   * 设置分享
   * @param isShare 是否需要分享
   * @param shareDetail 分享设置信息
   */
  setWXShare({ isShare = false, shareDetail = {} } = {}) {
    let shareMsg = {
      titleCircle: "", //分享到朋友圈title
      titleFriend: "", //分享给朋友title
      imgUrl: "", // 分享icon
      desc: "", // 分享到朋友圈的描述
      link: "" // 分享链接
    };

    isShare = isShare ? true : false;

    if (isShare) {
      return new Promise((resolve, reject) => {
        for (let [key, value] of Object.entries(shareDetail)) {
          switch (key) {
            case "title":
              shareMsg["titleCircle"] = shareMsg["titleFriend"] = value;
              break;
            case "titleCircle":
              shareMsg["titleCircle"] = value;
              break;
            case "titleFriend":
              shareMsg["titleFriend"] = value;
              break;
            case "imgUrl":
              shareMsg["imgUrl"] = value;
              break;
            case "desc":
              shareMsg["desc"] = value;
              break;
            case "link":
              shareMsg["link"] = value ? value : location.href;
              break;
            default:
              break;
          }
        }

        let menuList = this.menuListTemplate;

        wx.showMenuItems({
          menuList: menuList
        });

        //分享到朋友圈
        wx.onMenuShareTimeline({
          title: shareMsg.titleCircle,
          link: shareMsg.link,
          imgUrl: shareMsg.imgUrl,
          success() {
            resolve("sendTimeline");
          },
          cancel() {
            reject("sendTimeline");
          }
        });

        //分享给好友
        wx.onMenuShareAppMessage({
          title: shareMsg.titleFriend,
          desc: shareMsg.desc,
          imgUrl: shareMsg.imgUrl,
          link: shareMsg.link,
          success() {
            resolve("sendAppMessage");
          },
          cancel() {
            reject("sendAppMessage");
          }
        });
      });
    } else {
      this.forbidentShare();
    }
  },
  /**
   * 屏蔽分享
   */
  forbidentShare() {
    if (!window.wx) {
      function onBridgeReady() {
        typeof WeixinJSBridge != "undefined" &&
          WeixinJSBridge.call("hideOptionMenu");
      }

      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            onBridgeReady,
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
          document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
        }
      } else {
        onBridgeReady();
      }

      return;
    }

    wx.hideMenuItems({
      menuList: this.menuListTemplate
    });
  },
  //相册或者拍照上传文件
  imageUpload() {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        console.log(res);
        wx.uploadImage({
          localId: res.localIds[0], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: function(item) {
            var serverId = item.serverId; // 返回图片的服务器端ID
          }
        });
      }
    });
  }
};
